package com.htbb.base.util;

import java.util.Collections;
import java.util.List;

/**
 * 分页工具类
 * 
 * @author wangzhicheng
 *
 */
public class PageUtil<T> {

	/**
	 * 每页显示条数
	 */
	private int pageSize;

	/**
	 * 总页数
	 */
	private int pages;
	
	/**
	 * 总条数
	 */
	private int total;

	/**
	 * 分页的数据
	 */
	private List<T> list;
	
	/**
	 * 原集合
	 */
	private List<T> data;

	public PageUtil(List<T> data, int pageNum, int pageSize) {
		if (data == null || data.isEmpty()) {
			throw new IllegalArgumentException("list must be not empty!");
		}

		this.data = data;
		this.pageSize = pageSize;
		this.total = data.size();
		this.pages = data.size() / pageSize;
		if (data.size() % pageSize != 0) {
			this.pages++;
		}
		this.list = this.getPagedList(pageNum);
	}

	/**
	 * 得到分页后的数据
	 *
	 * @param pageNum
	 *            页码
	 * @return 分页后结果
	 */
	private List<T> getPagedList(int pageNum) {
		int fromIndex = (pageNum - 1) * pageSize;
		if (fromIndex >= data.size()) {
			return Collections.emptyList();
		}

		int toIndex = pageNum * pageSize;
		if (toIndex >= data.size()) {
			toIndex = data.size();
		}
		return data.subList(fromIndex, toIndex);
	}

	public int getPageSize() {
		return pageSize;
	}

	public List<T> getData() {
		return data;
	}

	public int getPages() {
		return pages;
	}

	public int getTotal() {
		return total;
	}

	public List<T> getList() {
		return list;
	}
}
